

import Vue from 'vue'
import flvjs from "flv.js";
import flash from "videojs-flash"
import videoflv from "videojs-flvjs"
import videojs from "video.js";

import "video.js/dist/video-js.css";



// import "./video.min.css";
// import "./flv.min";
// import "./videojs-flash.min.js";
// import "./videojs-flvjs.min.js"

Vue.component('fviz-media-video', {

  render: function (createElement) {

    let isAbsloute = true;
    let me = this;
    //图表容器样式
    let contStyle = {};

    if (isAbsloute) {
      contStyle.left = this.options.left + "px";
      contStyle.top = this.options.top + "px";
      contStyle.position = "absolute";
      //"z-index": (++cnt) * 30
    }

    //翻转样式
    if (this.options.turnAngle && this.options.turnAngle != 0) {
      contStyle["transform"] = "rotate(" + this.options.turnAngle + "deg)";
      contStyle["-ms-transform"] = "rotate(" + this.options.turnAngle + "deg)";
      contStyle["-moz-transform"] = "rotate(" + this.options.turnAngle + "deg)";
      contStyle["-webkit-transform"] = "rotate(" + this.options.turnAngle + "deg)";
      contStyle["-o-transform"] = "rotate(" + this.options.turnAngle + "deg)";
    }

    if (this.options.preview && !isAbsloute) {
      contStyle['width'] = '100%';
      contStyle['height'] = '100%';
    } else {
      contStyle['width'] = this.options.fwidth + "px";
      contStyle['height'] = this.options.fheight + "px";
    }

    if (this.options.borderWidth || this.options.borderColor || this.options.borderCornerValue) {
      contStyle['border'] = "solid";

    }
    contStyle['border-width'] = this.options.borderWidth;
    contStyle['border-color'] = this.options.borderColor;
    if (this.options.borderCorner) {
      if (this.options.borderCornerValue) {
        for (var i = 0; i < this.options.borderCornerValue.length; i++) {
          if (i == 0) {
            contStyle['border-top-left-radius'] = this.options.borderCornerValue[0] + "px";
          } else if (i == 1) {
            contStyle['border-top-right-radius'] = this.options.borderCornerValue[1] + "px";
          } else if (i == 2) {
            contStyle['border-bottom-right-radius'] = this.options.borderCornerValue[2] + "px";
          } else if (i == 3) {
            contStyle['border-bottom-left-radius'] = this.options.borderCornerValue[3] + "px";
          }
        }
      }

    };

    contStyle['border-radius'] = this.options.borderCornerValue + "px";
    contStyle['background-color'] = this.options.backgroudColor;


    let videoClass = { 'video-js': true, 'vjs-default-skin': true, 'vjs-big-play-centered': true };
    let videoContent = createElement('video', {
      ref: "videoPlayer",
      class: videoClass
    })




    let renderCont = createElement('div', {
      ref: "renderCont",
      style: contStyle,
    }, [videoContent])


    if (isAbsloute && !this.options.preview) {
      return createElement('div',
        [renderCont]
      );
    } else {
      return renderCont;
    }

  },
  data() {
    return {
      flag: true,
      options: "",
      player: null,
      type: "",
      videoOptions: {
        preload: true,
        autoplay: true,
        language: 'zh-CN',

        controls: true,
        // sources: [
        //     {
        //         src: "",
        //         type: ""
        //         //src: "http://localhost:82/1.flv",
        //         //src: "https://yunqivedio.alicdn.com/2017yq/v2/0x0/96d79d3f5400514a6883869399708e11/96d79d3f5400514a6883869399708e11.m3u8",
        //         //type: "application/x-mpegURL"
        //         // src: "http://www.ieforever.com/Site/cn/Uploads/media/20161118/%E6%81%92%E5%8D%8E%E7%A7%91%E6%8A%80-%E8%A7%86%E9%A2%91.mp4",
        //         // type: 'video/mp4'
        //         // type: 'video/x-flv'
        //     }
        // ],
        playbackRates: [0.5, 1, 1.5, 2],
        width: '900px',
        height: '400px',
        loop: true,
        controlBar: {
          volumePanel: {
            inline: false //默认是true,横着的
          },

        },
        techOrder: ['html5', 'flash'],



      },

    }
  },
  props: {
    objVal: {
      type: Object,
      default: () => {
        return {}
      }
    },
  },
  methods: {

    copyObj() {
      if (!Array.isArray) {
        Array.isArray = function (arg) {
          return Object.prototype.toString.call(arg) === '[object Array]';
        };
      }
      var name = void 0,
        options = void 0,
        src = void 0,
        copy = void 0,
        copyIsArray = void 0,
        clone = void 0,
        i = 1,
        target = arguments[0] || {},
        // 使用||运算符，排除隐式强制类型转换为false的数据类型
        deep = false,
        len = arguments.length;
      if (typeof target === 'boolean') {
        deep = target;
        target = arguments[1] || {};
        i++;
      }
      if ((typeof target === 'undefined' ? 'undefined' : this._typeof(target)) !== 'object' && typeof target !== 'function') {
        target = {};
      }
      // 如果arguments.length === 1 或typeof arguments[0] === 'boolean',且存在arguments[1]，则直接返回target对象
      if (i === len) {
        return target;
      }
      for (; i < len; i++) {
        //所以如果源对象中数据类型为Undefined或Null那么就会跳过本次循环，接着循环下一个源对象
        if ((options = arguments[i]) != null) {
          // 如果遇到源对象的数据类型为Boolean, Number for in循环会被跳过，不执行for in循环// src用于判断target对象是否存在name属性
          for (name in options) {
            // src用于判断target对象是否存在name属性
            src = target[name];
            // 需要复制的属性当前源对象的name属性
            copy = options[name];
            // 判断copy是否是数组
            copyIsArray = Array.isArray(copy);
            // 如果是深复制且copy是一个对象或数组则需要递归直到copy成为一个基本数据类型为止
            if (deep && copy && ((typeof copy === 'undefined' ? 'undefined' : this._typeof(copy)) === 'object' || copyIsArray)) {
              if (copyIsArray) {
                copyIsArray = false;
                // 如果目标对象存在name属性且是一个数组
                // 则使用目标对象的name属性，否则重新创建一个数组，用于复制
                clone = src && Array.isArray(src) ? src : [];
              } else {
                // 如果目标对象存在name属性且是一个对象则使用目标对象的name属性，否则重新创建一个对象，用于复制
                clone = src && (typeof src === 'undefined' ? 'undefined' : this._typeof(src)) === 'object' ? src : {};
              }
              // 深复制，所以递归调用copyObject函数
              // 返回值为target对象，即clone对象
              // copy是一个源对象
              target[name] = copyObj(deep, clone, copy);
            } else if (copy !== undefined) {
              // 浅复制，直接复制到target对象上
              target[name] = copy;
            }
          }
        }
      }
      return target;
    },
    _typeof() {
      return typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
    },
  },
  created() {

    this.options = this.copyObj({}, this.defaultOption, this.objVal);
    this.videoOptions.width = this.options.fwidth;
    this.videoOptions.height = this.options.fheight;
    // this.videoOptions.sources.src = this.options.dataUrl;
    this.videoOptions.loop = this.options.loopPlay.value;


    if (this.options.videoType) {
      if (this.options.videoType.value == 2) {
        this.type = "video/mp4";
      } else if (this.options.videoType.value == 3) {
        this.type = "video/x-flv"
      } else if (this.options.videoType.value == 4) {
        this.type = "application/x-mpegURL"
      } else if (this.options.videoType.value == 5) {
        this.type = "rtmp/flv"
      } else {

        if (this.options.dataUrl) {
          var index;
          let subType;
          if (this.options.dataUrl.length > 4) {
            index = this.options.dataUrl.indexOf(":");
            subType = this.options.dataUrl.substring(0, index);
            if (subType.indexOf("rtmp") != -1) {
              this.type = "rtmp/flv"
            } else {
              index = this.options.dataUrl.lastIndexOf(".");
              subType = this.options.dataUrl.substring(index);
              if (subType.indexOf("mp4") != -1) {
                this.type = "video/mp4";
              } else if (subType.indexOf("flv") != -1) {
                this.type = "video/x-flv"
              } else if (subType.indexOf("m3u8") != -1) {
                this.type = "application/x-mpegURL"
              }
            }
          }


        }

      }
    }




    // if (this.options.videoType) {
    //     if (this.options.videoType.value == 2) {
    //         this.videoOptions.sources.type = "video/mp4";
    //     } else if (this.options.videoType.value == 3) {
    //         this.videoOptions.sources.type = "video/x-flv"
    //     } else if (this.options.videoType.value == 4) {
    //         // this.videoOptions.sources.type = "application/x-mpegURL"
    //         this.videoOptions.sources.type = "rtmp/flv"
    //     } else {

    //         var index = this.options.dataUrl.lastIndexOf(".");

    //         let subType = this.options.dataUrl.substring(index);

    //         if (subType.indexOf("mp4") > 0) {
    //             this.videoOptions.sources.type = "video/mp4";
    //         } else if (subType.indexOf("flv") > 0) {
    //             this.videoOptions.sources.type = "video/x-flv"
    //         } else if (subType.indexOf("m3u8") > 0) {
    //             this.videoOptions.sources.type = "application/x-mpegURL"
    //         }
    //     }
    // }



  },
  watch: {
    flag(newData, oldData) {
      let me = this;
      if (newData == true && this.type.indexOf("rtmp") != -1) {
        // window.location.reload();

        // this.player.off('timeupdate');
        // this.player.reset()
        // this.player.src({
        //     src: this.options.dataUrl,
        //     type: this.type

        // });

        this.player.load(this.options.dataUrl);



        //this.player.currentTime(3200);//设置播放的当前时间
        //this.player.playbackRate(5);//设置播放速度

      }
    }
  },
  computed: {
    defaultOption() {
      return {

        fwidth: 750,
        fheight: 400,
        defaultVolume: 0.5,
        loopPlay: {
          name: "是",
          value: true
        },

      }
    },
  },
  mounted() {
    var me = this
    console.log(this.videoOptions)
    if (this.options.preview && !true) {
      this.options.fwidth = this.$refs.renderCont.offsetWidth;
      this.options.fheight = this.$refs.renderCont.offsetHeight;
      this.videoOptions.width = this.options.fwidth;
      this.videoOptions.height = this.options.fheight;
    }
    videojs.addLanguage('zh-CN', {
      "Play": "播放",
      "Pause": "暂停",
      "Current Time": "当前时间",
      "Duration": "时长",
      "Remaining Time": "剩余时间",
      "Stream Type": "媒体流类型",
      "LIVE": "直播",
      "Loaded": "加载完毕",
      "Progress": "进度",
      "Fullscreen": "全屏",
      "Non-Fullscreen": "退出全屏",
      "Mute": "静音",
      "Unmute": "取消静音",
      "Playback Rate": "播放速度",
      "Subtitles": "字幕",
      "subtitles off": "关闭字幕",
      "Captions": "内嵌字幕",
      "captions off": "关闭内嵌字幕",
      "Chapters": "节目段落",
      "Close Modal Dialog": "关闭弹窗",
      "Descriptions": "描述",
      "descriptions off": "关闭描述",
      "Audio Track": "音轨",
      "You aborted the media playback": "视频播放被终止",
      "A network error caused the media download to fail part-way.": "网络错误导致视频下载中途失败。",
      "The media could not be loaded, either because the server or network failed or because the format is not supported.": "视频因格式不支持或者服务器或网络的问题无法加载。",
      "The media playback was aborted due to a corruption problem or because the media used features your browser did not support.": "由于视频文件损坏或是该视频使用了你的浏览器不支持的功能，播放终止。",
      "No compatible source was found for this media.": "无法找到此视频兼容的源。",
      "The media is encrypted and we do not have the keys to decrypt it.": "视频已加密，无法解密。",
      "Play Video": "播放视频",
      "Close": "关闭",
      "Modal Window": "弹窗",
      "This is a modal window": "这是一个弹窗",
      "This modal can be closed by pressing the Escape key or activating the close button.": "可以按ESC按键或启用关闭按钮来关闭此弹窗。",
      ", opens captions settings dialog": ", 开启标题设置弹窗",
      ", opens subtitles settings dialog": ", 开启字幕设置弹窗",
      ", opens descriptions settings dialog": ", 开启描述设置弹窗",
      ", selected": ", 选择",
      "captions settings": "字幕设定",
      "Audio Player": "音频播放器",
      "Video Player": "视频播放器",
      "Replay": "重播",
      "Progress Bar": "进度条",
      "Volume Level": "音量",
      "subtitles settings": "字幕设定",
      "descriptions settings": "描述设定",
      "Text": "文字",
      "White": "白",
      "Black": "黑",
      "Red": "红",
      "Green": "绿",
      "Blue": "蓝",
      "Yellow": "黄",
      "Magenta": "紫红",
      "Cyan": "青",
      "Background": "背景",
      "Window": "视窗",
      "Transparent": "透明",
      "Semi-Transparent": "半透明",
      "Opaque": "不透明",
      "Font Size": "字体尺寸",
      "Text Edge Style": "字体边缘样式",
      "None": "无",
      "Raised": "浮雕",
      "Depressed": "压低",
      "Uniform": "均匀",
      "Dropshadow": "下阴影",
      "Font Family": "字体库",
      "Proportional Sans-Serif": "比例无细体",
      "Monospace Sans-Serif": "单间隔无细体",
      "Proportional Serif": "比例细体",
      "Monospace Serif": "单间隔细体",
      "Casual": "舒适",
      "Script": "手写体",
      "Small Caps": "小型大写字体",
      "Reset": "重置",
      "restore all settings to the default values": "恢复全部设定至预设值",
      "Done": "完成",
      "Caption Settings Dialog": "字幕设定视窗",
      "Beginning of dialog window. Escape will cancel and close the window.": "开始对话视窗。离开会取消及关闭视窗",
      "End of dialog window.": "结束对话视窗",
      "Seek to live, currently behind live": "试图直播，当前延时播放",
      "Seek to live, currently playing live": "试图直播，当前实时播放",
      "progress bar timing: currentTime={1} duration={2}": "{1}/{2}",
      "{1} is loading.": "正在加载 {1}。",
      "Picture-in-Picture": "画中画"
    });
    this.player = videojs(this.$refs.videoPlayer, this.videoOptions, function onPlayerReady() {
      // this.player.load(this.videoOptions.sources.src);
      // this.player.play();
    })
    this.player.off('timeupdate');
    this.player.reset()
    if (this.options.dataUrl) {
      this.player.src({
        src: this.options.dataUrl,
        type: this.type

      });
    }

    this.player.load(this.options.dataUrl);
    console.log(this.options.defaultVolume);
    this.player.volume(this.options.defaultVolume);//设置音量

    //this.player.currentTime(3200);//设置播放的当前时间
    //this.player.playbackRate(5);//设置播放速度


    this.player.on("play", function () {//播放视频时候使用
      me.flag = true
      console.log("play", me.flag)
    });


    this.player.on("pause", function () {//关闭视频时候使用
      me.flag = false
      console.log("pause", me.flag)

    });
    this.player.on("ended", function () {
      console.log("end", this.currentTime());
    });


  },

})